package iPod;

import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.TreeMap;

public class IPod {

	protected TreeMap<String, TrackItem> tracklist = new TreeMap<String, TrackItem>();
	
	public void load(String controlPath)
	{
	    // Read the track database:
		Database db = new Database();
		
		try
		{
			RandomAccessFile raf = new RandomAccessFile(controlPath + "\\iTunesDB", "r");			
		    db.load(raf);
		    raf.close();
		}
		catch (Exception e)
		{
			System.out.println("Failed to read database file");
		}
	    		    
	    TrackList trackList = (TrackList)db.getTracklist().getDatalist();
	    if (trackList == null)
	    {
	    	System.out.println("Read input database failed");
	    	return;
	    }
	    	
	    PlayCountList playcounts = new PlayCountList();
	    
	    try
	    {
		    RandomAccessFile raf = new RandomAccessFile(controlPath + "\\Play Counts", "r");		    		    
		    playcounts.load(raf);
		    raf.close();
		}
		catch (Exception e)
		{
			System.out.println("Failed to read playcounts file");
		}
		
	    GenerateTrackDatabase(trackList, playcounts);		   		   
	}
	
	public String GenerateTrackKey(String artist, String album, String title, int filesize)
	{
		String key = "";
		key += artist;
		key += "|" + album;
		key += "|" + title;
		key += "|" + filesize;
		
		return key;
	}
	
	public TrackItem GetTrackRecord(String key)
	{
		return tracklist.get(key);
	}
	
	public TrackItem GetTrackRecord(String artist, String album, String title, int filesize)
	{
		return GetTrackRecord(GenerateTrackKey(artist,album,title,filesize));
	}
	
	private void GenerateTrackDatabase(TrackList datalist, PlayCountList playcountlist) {
		ArrayList<TrackItem> items = datalist.getTracklist();
		ArrayList<PlayCountItem> playcounts = playcountlist.getPlaycountlist();		
		
		if (playcounts.size() != items.size())
		{
			System.out.println("database and playcounts are not in sync");
			playcounts = null;
		}
		
		for (int index = 0; index < items.size(); ++index)
		{
			TrackItem curItem = items.get(index);
			if (playcounts != null)
			{
				PlayCountItem countItem = playcounts.get(index);
				curItem.setRating(countItem.getRating());
			}
			
			String key = GenerateTrackKey(curItem.getArtist(), curItem.getAlbum(), 
					curItem.getTitle(), curItem.getFileSize());
			
			tracklist.put(key, curItem);
		}
	}
}
